package com.gd.deron.smartrobot.baobao.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.widget.Toast;

public class FileUtils {

	
	/** 获取设备id */
	public static String getRobotId() {
		StringBuffer buffer = new StringBuffer();
		try {
			Log.e("FileUtil", Environment.getExternalStorageDirectory().getPath());
			String path01 = Environment.getExternalStorageDirectory().getPath() + "/robotbaobaoid.txt";
			File urlFile01 = new File(path01);
			if (urlFile01.exists()) {
				//字符流
				InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile01), "UTF-8");
				BufferedReader br = new BufferedReader(isr);
				
				String mimeTypeLine = null;
				while ((mimeTypeLine = br.readLine()) != null) {
					buffer.append(mimeTypeLine);
				}
				return buffer.toString();
			} else{
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/** sd卡是否存在 */
	public static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}
	public static String readCallToSD(String fileName,String format) {
		StringBuffer buffer = new StringBuffer();
		try {
			String path01 = Environment.getExternalStorageDirectory().getPath() + "/"+fileName;
			File urlFile01 = new File(path01);
			if (urlFile01.exists()) {
				InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile01), format);
				BufferedReader br = new BufferedReader(isr);
				
				String mimeTypeLine = null;
				while ((mimeTypeLine = br.readLine()) != null) {
					buffer.append(mimeTypeLine+"\n");
				}
				return buffer.toString();
			} else{
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 
	 * 描述：追加内容到文件末尾 
	 * @author caiqingming 
	 * @isAdd 是否追加内容
	 * 
	 */  
	public static void wridCalltoSd(String conent,boolean isAdd,String fileName){
		 BufferedWriter out = null;  
	        try {  
	        	String path = Environment.getExternalStorageDirectory().getPath() + "/"+fileName;
	            out = new BufferedWriter(new OutputStreamWriter(  
	                    new FileOutputStream( new File(path), isAdd)));  
	            out.write(conent);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            try {  
	                out.close();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	        }  
		
	}
	public static String readCallToSD() {
		StringBuffer buffer = new StringBuffer();
		try {
			String path01 = Environment.getExternalStorageDirectory().getPath() + "/call.bnf";
			File urlFile01 = new File(path01);
			if (urlFile01.exists()) {
				InputStreamReader isr = new InputStreamReader(new FileInputStream(urlFile01), "UTF-8");
				BufferedReader br = new BufferedReader(isr);
				
				String mimeTypeLine = null;
				while ((mimeTypeLine = br.readLine()) != null) {
					buffer.append(mimeTypeLine+"\n");
				}
				return buffer.toString();
			} else{
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 
	 * 描述：追加内容到文件末尾 
	 * @author caiqingming 
	 * @isAdd 是否追加内容
	 * 
	 */  
	public static void wridCalltoSd(String conent,boolean isAdd){
		 BufferedWriter out = null;  
	        try {  
	        	String path = Environment.getExternalStorageDirectory().getPath() + "/call.bnf";
				File urlFile = new File(path);
	            out = new BufferedWriter(new OutputStreamWriter(  
	                    new FileOutputStream(urlFile, isAdd)));  
	            out.write(conent);  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        } finally {  
	            try {  
	                out.close();  
	            } catch (IOException e) {  
	                e.printStackTrace();  
	            }  
	        }  
		
	}
	/** 
	 * 获取SD卡根目录路径 
	 *  
	 * @return 
	 */  
	public static String getSdCardPath() {  
	    boolean exist = isSdCardExist();  
	    String sdpath = "";  
	    if (exist) {  
	        sdpath = Environment.getExternalStorageDirectory()  
	                .getAbsolutePath();  
	    } else {  
	        sdpath = "不适用";  
	    }  
	    return sdpath;  
	  
	}  
	/** 
	 * 判断SDCard是否存在 [当没有外挂SD卡时，内置ROM也被识别为存在sd卡] 
	 *  
	 * @return 
	 */  
	public static boolean isSdCardExist() {  
	    return Environment.getExternalStorageState().equals(  
	            Environment.MEDIA_MOUNTED);  
	} 

	/** 可以在不存在的目录中创建文件夹 */
	public static File mkdirsOnSDCard(String pathName) {
		File file = new File(Environment.getExternalStorageDirectory(), pathName);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}

	public static boolean copy(String input, String output) throws Exception {
		int BUFSIZE = 65536;
		try {
			FileInputStream fis = new FileInputStream(input);
			FileOutputStream fos = new FileOutputStream(output);

			int s;
			byte[] buf = new byte[BUFSIZE];
			while ((s = fis.read(buf)) > -1) {
				fos.write(buf, 0, s);
			}
		} catch (Exception ex) {
			throw new Exception("makehome" + ex.getMessage());
		}
		return true;
	}

	public static boolean checkSDCard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED))
			return true;
		else
			return false;
	}

	/**
	 * 刷新sd内容
	 */
	public static void refreshContent(Context context, String path) {
		Uri data = Uri.parse("file://" + path);
		context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
	}

	/**
	 * 
	 * @param 获取sd卡容量
	 * @return
	 */
	public static double getSdCardContent() {
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			File path = Environment.getExternalStorageDirectory();
			StatFs sf = new StatFs(path.getPath());
			long blockSize = sf.getBlockSize();
			long freeBlocks = sf.getAvailableBlocks();
			return (freeBlocks * blockSize) / 1024 / 1024;
		} else {
			return 0;
		}
	}

	/**
	 * 将输入流转换成字符串
	 * 
	 * @param inStream
	 */
	public static String convertString(InputStream inStream) {
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream();
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = inStream.read(buf)) > 0) {
				bos.write(buf, 0, len);
			}
			return new String(bos.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bos != null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;

	}

	/**
	 * 创建临时文件
	 * 
	 * @param srcPath
	 * @param destPath
	 * @return
	 */
	public static boolean createTempFile(String srcPath, String destPath) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {

			FileInputStream in = new FileInputStream(srcPath);
			bis = new BufferedInputStream(in);
			bos = new BufferedOutputStream(new FileOutputStream(destPath));
			int len = 0;
			byte[] buf = new byte[4098];
			while ((len = bis.read(buf)) > 0) {
				bos.write(buf, 0, len);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static byte[] res2byte(Context context, int resId) {
		Bitmap bm = BitmapFactory.decodeResource(context.getResources(), resId);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
		try {
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bos.toByteArray();
	}

	/** 创建文件 */
	public static File createFile(String url) {
		File cacheDir = new File(Environment.getExternalStorageDirectory(), url);
		if (!cacheDir.exists()) {
			cacheDir.mkdirs();
		}
		return cacheDir;
	}

	/** 删除文件 */
	public static void deleteFile(String name, String url) {
		File cacheDir = new File(Environment.getExternalStorageDirectory(), url);
		File f = new File(cacheDir, name);
		if (f.exists()) {
			f.delete();
		}
	}

	/** 删除文件 */
	public static void deleteFile(String url) {
		File file = new File(url);
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete();
			}
			file.delete();
		}
	}

	/** 删除目录 */
	public static void deletelistFiles(String url) {
		File cacheDir = new File(Environment.getExternalStorageDirectory(), url);
		if (null != cacheDir) {
			File[] file = cacheDir.listFiles();
			if (null != file) {
				if (file.length > 0) {
					for (int i = 0; i < file.length; i++) {
						file[i].delete();
					}
				}
			}
		}
	}

	/**获取文件的大小*/
	@SuppressWarnings("resource")
	public static long getFileSizes(File f) throws Exception {
		long s = 0;
		if (f.exists()) {
			FileInputStream fis = null;
			fis = new FileInputStream(f);
			s = fis.available();
		} else {
			f.createNewFile();
			System.out.println("文件不存在");
		}
		return s;
	}
	/**
	 * @param Path 获取制定路径的
	 * @param Extension 指定文件后缀的文件
	 * @author IsIterative 是否进入子文件夹
	 * */

	/**获取制定路径的、制定文件后缀的文件*/
	public static List<File> GetFiles(String Path, String[] Extensions, boolean IsIterative,List<File> mList)  //搜索目录，扩展名，是否进入子文件夹  
    {  
        File[] files = new File(Path).listFiles();  
        
        File f;  
        if(files == null)  
        {  
            return null;  
        }  
        for (int i = 0; i < files.length; i++)  
        {  
            f = files[i];  
            if(!f.canRead())  
            {  
                return null;  
            }  
            if (f.isFile())  //文件
            {  
            	for(String exten:Extensions){
            		if(f.getName().endsWith(exten)){//判断扩展名                    
            			mList.add(f);
                        //  Log.e(TAG,"文件="+f.getPath());
            		}
            	} 
               
            }else if (f.isDirectory()){//目录
            	//Log.e(TAG,"目录="+f.getPath()); 
            	GetFiles(f.getPath(), Extensions, IsIterative,mList);  
            }
            
        }  
       // Log.e(TAG,"mList数量="+mList.size());
        return mList;   
    }
}
